<?php
/**
 * Copyright (c) 2008 Derdubor A/S
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/** @see Keepitclose_Storage_Interface */
require_once 'Keepitclose/Storage/Interface.php';

class Keepitclose_Saver
{
    /**
     * The current TTL.
     *
     * @var int
     */
    protected $ttl;
    
    /**
     * The storage module this saver uses.
     *
     * @var Keepitclose_Storage
     */
    protected $storage;

    /**
     * Constructor for the Saver itself, using the provided Storage module for caching.
     *
     * @param Keepitclose_Storage $storage The storage module to use for access cached resources.
     */
    public function __construct(Keepitclose_Storage $storage)
    {
        $this->setStorage($storage);
    }

    /**
     * Set the storage module to use in this saver for caching.
     *
     * @param Keepitclose_Storage $storage The storage module.
     */
    public function setStorage(Keepitclose_Storage $storage)
    {
        $this->storage = $storage;
    }

    /**
     * Get the storage module of this saver.
     * 
     * @return Keepitclose_Storage The current storage module in use.
     */
    public function getStorage()
    {
        return $this->storage;
    }
    
    /**
     * Set the TTL of this Saver
     *
     * @param $ttl int The time to live to use when saving something in the storage module.
     */
    public function setTTL($ttl)
    {
        $this->ttl = (int) $ttl;
    }

    /**
     * Get the TTL setting of this saver.
     *
     * @return int The TTL (time to live) this saver uses when saving something to the cache.
     */
    public function getTTL()
    {
        return $this->ttl;
    }

    /**
     * Get the contents of an URL, using the cached version if it's still within the TTL.
     *
     * @param string $url The URL to retrieve.
     * @param boolean $noCache Wether to use the cache or not; if false, do not use cache (will not store the retrieved content either)
     * @return The retrieved data, false on failure
     */
    public function get($url, $noCache = false)
    {
        $data = false;
    
        if(!$noCache)
        {
            $data = $this->getStorage()->get($url);

            if ($data !== false)
            {
                return $data;
            }
        }
        
        $URLparts = parse_url($url);
        
        if ($URLparts)
        {
            switch($URLparts['scheme'])
            {
                case 'http':
                case 'https':
                    if(!empty($URLparts['path']))
                    {
                        $URLparts['path'] = urlencode($URLparts['path']);
                    }
                    
                    // / we have to keep / as it is.
                    $url = str_replace(array('%2F', '%2f'), '/', $this->joinURL($URLparts));
                
                    $curl = curl_init($url);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($curl, CURLOPT_HEADER, true);
                    $read = curl_exec($curl);
                    
                    $splitpoint = strpos($read, "\r\n\r\n");
                    
                    $data = array(
                        'headers' => array(),
                        'content' => substr($read, $splitpoint + 4),
                    );

                    $headers = explode("\n", substr($read, 0, $splitpoint));

                    foreach($headers as $header)
                    {
                        $parts = explode(':', $header);
                        
                        if (count($parts) > 1)
                        {
                            $data['headers'][] = array(
                                'key' => trim(array_shift($parts)),
                                'value' => trim(join(':', $parts)),
                            );
                        }
                    }
                    
                    curl_close($curl);
                    
                    break;
            }
        
            // if we got any proper data, store and return it.
            if(($data !== false) && !$noCache)
            {
                $this->getStorage()->set($url, $data, $this->getTTL());
            }
        }
        
        return $data;
    }
    
    /**
     * Join a URL that has been exploded with parse_url.
     *
     * @param array $urlParts An array from parse_url.
     * @return string The resulting URL after glueing everything back together.
     */
    protected function joinURL(array $urlParts)
    {
        $url = (!empty($urlParts['scheme']) ? $urlParts['scheme'] . '://' : '') .
               (!empty($urlParts['user']) ? $urlParts['user'] : '') .
               (!empty($urlParts['pass']) ? ':' . $urlParts['pass'] : '') .
               (!empty($urlParts['user']) ? '@' : '') .
               (!empty($urlParts['host']) ? $urlParts['host'] : '') .
               (!empty($urlParts['port']) ? ':' . $urlParts['port'] : '') .
               (!empty($urlParts['path']) ? $urlParts['path'] : '') .
               (!empty($urlParts['query']) ? '?' . $urlParts['query'] : '') .
               (!empty($urlParts['fragment']) ? '#' . $urlParts['fragment'] : '');

        return $url;
    }
}